package cn.outsourcing.supermarket.controller;

import cn.outsourcing.supermarket.common.Result;
import cn.outsourcing.supermarket.common.exception.SupermarketException;
import cn.outsourcing.supermarket.common.utils.ResultUtils;
import cn.outsourcing.supermarket.dto.AddCartDTO;
import cn.outsourcing.supermarket.dto.CartCheckedDTO;
import cn.outsourcing.supermarket.service.HiolabsCartService;
import cn.outsourcing.supermarket.vo.CartCountVO;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 购物车前端控制器
 *
 * @author gzkemays
 * @since 2021-10-20
 */
@RestController
@RequestMapping("/cart")
public class HiolabsCartController {
  @Resource HiolabsCartService cartService;

  @GetMapping("/checkout")
  public Result getCartCheckOut(CartCheckedDTO entity) {
    return ResultUtils.simpleResult(cartService.checkedCart(entity));
  }

  @GetMapping("/goodsCount")
  public Result getGoodsCount() {
    return ResultUtils.simpleResult(
        CartCountVO.builder().cartTotal(cartService.getCartTotal()).build());
  }

  @PostMapping("/add")
  public Result add(@RequestBody AddCartDTO entity) {
    return ResultUtils.simpleResult(cartService.add(entity));
  }

  @PostMapping("/update")
  public Result update(@RequestBody AddCartDTO entity) {
    return ResultUtils.simpleResult(cartService.updateByEntity(entity));
  }

  @GetMapping("/index")
  public Result index() {
    return ResultUtils.simpleResult(cartService.index());
  }

  @PostMapping("/delete")
  public Result delete(@RequestBody Map<String, Integer> productIds) {
    Integer productId = productIds.get("productIds");
    if (productId == null) {
      return ResultUtils.exception(new SupermarketException(-999, "错误参数"));
    }
    return ResultUtils.simpleResult(cartService.deleteGoods(productId));
  }

  @PostMapping("/checked")
  public Result checked(@RequestBody Map<String, Object> entity) {
    return ResultUtils.simpleResult(cartService.checkedGoods(entity));
  }
}
